<template>
  <div class="homework-container">
    <div class="main-content">
      <div class="selection-panel">
        <h2>习题生成配置</h2>
        
        <!-- 学习阶段选择 -->
        <div class="form-item">
          <label>学习阶段</label>
          <el-select v-model="formData.stage" placeholder="请选择学习阶段" @change="handleStageChange">
            <el-option
              v-for="item in stages"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </div>

        <!-- 学习科目选择 -->
        <div class="form-item">
          <label>学习科目</label>
          <el-select v-model="formData.subject" placeholder="请选择学习科目" @change="handleSubjectChange">
            <el-option
              v-for="item in subjects"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </div>

        <!-- 课本教材选择 -->
        <div class="form-item">
          <label>课本教材</label>
          <el-select v-model="formData.textbook" placeholder="请选择课本教材" @change="handleTextbookChange">
            <el-option
              v-for="item in textbooks"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </div>

        <!-- 章节选择 -->
        <div class="form-item">
          <label>章节</label>
          <el-select v-model="formData.chapter" placeholder="请选择章节" multiple>
            <el-option
              v-for="item in chapters"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </div>

        <!-- 习题数量选择 -->
        <div class="form-item">
          <label>习题数量</label>
          <el-input-number v-model="formData.exerciseCount" :min="1" :max="50" />
        </div>

        <!-- 习题类型选择 -->
        <div class="form-item">
          <label>习题类型</label>
          <el-checkbox-group v-model="formData.exerciseTypes">
            <el-checkbox label="judgment">判断题</el-checkbox>
            <el-checkbox label="choice">选择题</el-checkbox>
            <el-checkbox label="fill">填空题</el-checkbox>
            <el-checkbox label="essay">简答题</el-checkbox>
          </el-checkbox-group>
        </div>
      </div>

      <div class="action-panel">
        <el-button type="primary" @click="generateExercises" :loading="generating">
          生成习题
        </el-button>
      </div>

      <!-- 显示大模型原始输出 -->
      <el-card v-if="modelResponse" class="model-response-card">
        <template #header>
          <div class="card-header">
            <h3>大模型原始输出</h3>
          </div>
        </template>
        <pre class="model-response-content">{{ modelResponse }}</pre>
      </el-card>

      <div v-if="exercises.length > 0" class="exercises-list">
        <h2>生成的习题</h2>
        <div v-for="(exercise, index) in exercises" :key="index" class="exercise-item">
          <div class="exercise-header">
            <span class="exercise-type">{{ getExerciseTypeLabel(exercise.type) }}</span>
            <span class="exercise-number">第 {{ index + 1 }} 题</span>
          </div>
          <div class="exercise-content">
            <div class="question-title">
              <strong>题目：</strong>{{ exercise.content }}
            </div>
            <div v-if="exercise.options" class="exercise-options">
              <div v-for="(optionText, optKey) in exercise.options" :key="optKey" class="option-item">
                <strong>{{ optKey }}、</strong>{{ optionText }}
              </div>
            </div>
          </div>
          <div class="exercise-footer">
            <el-button type="text" @click="toggleAnswer(index)" class="toggle-btn">
              {{ showAnswers[index] ? '隐藏答案和解析' : '显示答案和解析' }}
            </el-button>
            <div v-if="showAnswers[index]" class="answer-section">
              <div class="answer-content">
                <strong>答案：</strong>{{ exercise.answer }}
              </div>
              <div class="explanation-content">
                <strong>解析：</strong>{{ exercise.explanation }}
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 历史记录预览面板 -->
    <div class="history-panel">
      <h3>历史记录</h3>
      <div class="history-list">
        <div v-for="(item, index) in historyList" 
             :key="index"
             :class="['history-item', { active: selectedHistory === index }]"
             @click="selectHistory(index)">
          <div class="history-title">{{ item.title }}</div>
          <div class="history-time">{{ item.time }}</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'

// 表单数据
const formData = ref({
  stage: '',
  subject: '',
  textbook: '',
  chapter: [],
  exerciseCount: 10,
  exerciseTypes: ['choice']
})

// 选项数据
const stages = ref([
  { value: 'primary', label: '小学' },
  { value: 'junior', label: '初中' },
  { value: 'senior', label: '高中' },
  { value: 'university', label: '大学' }
])

// 模拟科目数据
const subjectsMap = {
  primary: [
    { value: 'math', label: '数学' },
    { value: 'chinese', label: '语文' },
    { value: 'english', label: '英语' }
  ],
  junior: [
    { value: 'math', label: '数学' },
    { value: 'chinese', label: '语文' },
    { value: 'english', label: '英语' },
    { value: 'physics', label: '物理' },
    { value: 'chemistry', label: '化学' }
  ],
  senior: [
    { value: 'math', label: '数学' },
    { value: 'chinese', label: '语文' },
    { value: 'english', label: '英语' },
    { value: 'physics', label: '物理' },
    { value: 'chemistry', label: '化学' },
    { value: 'biology', label: '生物' }
  ],
  university: [
    { value: 'math', label: '高等数学' },
    { value: 'physics', label: '大学物理' },
    { value: 'chemistry', label: '大学化学' }
  ]
}

// 模拟教材数据
const textbooksMap = {
  math: [
    { value: 'pep_math_1', label: '人教版数学一年级上册' },
    { value: 'pep_math_2', label: '人教版数学一年级下册' },
    { value: 'pep_math_3', label: '人教版数学二年级上册' },
    { value: 'pep_math_4', label: '人教版数学二年级下册' }
  ],
  chinese: [
    { value: 'pep_chinese_1', label: '人教版语文一年级上册' },
    { value: 'pep_chinese_2', label: '人教版语文一年级下册' },
    { value: 'pep_chinese_3', label: '人教版语文二年级上册' },
    { value: 'pep_chinese_4', label: '人教版语文二年级下册' }
  ],
  english: [
    { value: 'pep_english_1', label: '人教版英语一年级上册' },
    { value: 'pep_english_2', label: '人教版英语一年级下册' },
    { value: 'pep_english_3', label: '人教版英语二年级上册' },
    { value: 'pep_english_4', label: '人教版英语二年级下册' }
  ]
}

// 模拟章节数据
const chaptersMap = {
  pep_math_1: [
    { value: 'chapter_1', label: '第一章 数与代数' },
    { value: 'chapter_2', label: '第二章 图形与几何' },
    { value: 'chapter_3', label: '第三章 统计与概率' }
  ],
  pep_math_2: [
    { value: 'chapter_1', label: '第一章 数与运算' },
    { value: 'chapter_2', label: '第二章 空间与图形' },
    { value: 'chapter_3', label: '第三章 应用题' }
  ],
  pep_chinese_1: [
    { value: 'chapter_1', label: '第一单元 识字' },
    { value: 'chapter_2', label: '第二单元 课文' },
    { value: 'chapter_3', label: '第三单元 古诗' }
  ],
  pep_english_1: [
    { value: 'chapter_1', label: 'Unit 1 Hello!' },
    { value: 'chapter_2', label: 'Unit 2 My Family' },
    { value: 'chapter_3', label: 'Unit 3 Numbers' }
  ]
}

const subjects = ref([])
const textbooks = ref([])
const chapters = ref([])

// 大模型响应数据
const modelResponse = ref('')

// 习题相关
const exercises = ref([])
const showAnswers = ref([])
const generating = ref(false)

// 历史记录相关
const historyList = ref([
  { title: '数学第一章习题', time: '2024-03-20 14:30' },
  { title: '语文古诗练习', time: '2024-03-19 16:45' },
  { title: '英语语法练习', time: '2024-03-18 09:15' },
  { title: '物理实验题', time: '2024-03-17 11:20' }
])
const selectedHistory = ref(null)

// 处理学习阶段变化
const handleStageChange = async (value) => {
  formData.value.subject = ''
  formData.value.textbook = ''
  formData.value.chapter = []
  
  try {
    const response = await axios.get(`/api/subjects?stage=${value}`)
    subjects.value = response.data
  } catch (error) {
    ElMessage.error('获取科目列表失败')
  }
}

// 处理科目变化
const handleSubjectChange = async (value) => {
  formData.value.textbook = ''
  formData.value.chapter = []
  
  try {
    const response = await axios.get(`/api/textbooks?subject=${value}`)
    textbooks.value = response.data
  } catch (error) {
    ElMessage.error('获取教材列表失败')
  }
}

// 处理教材变化
const handleTextbookChange = async (value) => {
  formData.value.chapter = []
  
  try {
    const response = await axios.get(`/api/chapters?textbook=${value}`)
    chapters.value = response.data
  } catch (error) {
    ElMessage.error('获取章节列表失败')
  }
}

// 生成习题
const generateExercises = async () => {
  if (!formData.value.stage || !formData.value.subject || !formData.value.textbook || formData.value.chapter.length === 0) {
    ElMessage.warning('请完善习题生成配置')
    return
  }
  
  if (formData.value.exerciseTypes.length === 0) {
    ElMessage.warning('请至少选择一种习题类型')
    return
  }
  
  generating.value = true
  try {
    // 将前端参数名与后端参数名匹配
    const requestData = {
      stage: formData.value.stage,
      subject: formData.value.subject,
      grade: formData.value.stage, // 使用学习阶段作为年级
      knowledgePoint: formData.value.chapter.join(','), // 将章节作为知识点
      questionCount: formData.value.exerciseCount,
      questionTypes: formData.value.exerciseTypes,
      difficultyLevel: '中等', // 默认设置为中等难度
    };
    
    console.log('发送请求数据:', requestData);
    const response = await axios.post('/api/teaching/generate-exercises', requestData);
    
    // 处理后端返回的数据，确保能正确获取exercises数组
    console.log('后端返回数据:', response.data);
    
    // 保存原始响应数据
    if (response.data && response.data.originalResponse) {
      modelResponse.value = response.data.originalResponse;
    } else if (response.data && response.data.data) {
      modelResponse.value = typeof response.data.data === 'string' 
        ? response.data.data 
        : JSON.stringify(response.data.data, null, 2);
    } else {
      modelResponse.value = JSON.stringify(response.data, null, 2);
    }
    
    // 根据返回格式调整获取exercises的方式
    let exercisesData = [];
    
    if (response.data.data) {
      // 尝试解析data字段中的JSON字符串
      try {
        let parsedData;
        // 首先检查是否是字符串类型
        if (typeof response.data.data === 'string') {
          let jsonStr = response.data.data;
          
          // 检查并处理可能的Markdown代码块格式
          if (jsonStr.includes('```json')) {
            // 去除```json和结尾的```
            jsonStr = jsonStr.replace(/```json\n/g, '').replace(/\n```$/g, '');
          }
          
          parsedData = JSON.parse(jsonStr);
        } else {
          parsedData = response.data.data;
        }
        
        // 检查解析后的数据中是否有exercises字段
        if (parsedData.exercises) {
          exercisesData = parsedData.exercises;
        } else if (Array.isArray(parsedData)) {
          // 如果本身就是数组，直接使用
          exercisesData = parsedData;
        } else {
          // 尝试找到可能的题目数组
          console.log('尝试在解析数据中查找题目数组');
          console.log(parsedData);
          
          // 如果数据是包含题目的对象，尝试解析
          for (const key in parsedData) {
            if (Array.isArray(parsedData[key]) && parsedData[key].length > 0) {
              if (parsedData[key][0].type || parsedData[key][0].content) {
                exercisesData = parsedData[key];
                break;
              }
            }
          }
        }
      } catch (e) {
        console.error('解析习题数据失败:', e);
        ElMessage.warning('习题数据格式异常，请查看控制台');
      }
    } else if (response.data.exercises) {
      // 直接获取exercises字段
      exercisesData = response.data.exercises;
    } else if (Array.isArray(response.data)) {
      // response.data本身就是数组
      exercisesData = response.data;
    }
    
    exercises.value = exercisesData;
    showAnswers.value = new Array(exercises.value.length).fill(false);
    
    if (exercises.value.length > 0) {
      ElMessage.success('习题生成成功');
    } else {
      ElMessage.warning('未能正确解析习题数据，请检查接口返回格式');
    }
  } catch (error) {
    ElMessage.error('习题生成失败')
  } finally {
    generating.value = false
  }
}

// 切换答案显示
const toggleAnswer = (index) => {
  showAnswers.value[index] = !showAnswers.value[index]
}

// 获取习题类型标签
const getExerciseTypeLabel = (type) => {
  const typeMap = {
    judgment: '判断题',
    choice: '选择题',
    fill: '填空题',
    essay: '简答题'
  }
  return typeMap[type] || type
}

const selectHistory = (index) => {
  selectedHistory.value = index
  // 这里可以添加加载历史记录的逻辑
}

onMounted(() => {
  // 初始化加载
  if (formData.value.stage) {
    handleStageChange(formData.value.stage)
  }
})
</script>

<style scoped>
.homework-container {
  max-width: 1200px;
  margin: 0 auto;
  display: flex;
  gap: 20px;
}

.main-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 20px;
  margin-top: 0px;
}

.history-panel {
  width: 300px;
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  height: fit-content;
}

.history-panel h3 {
  margin-bottom: 15px;
  color: #333;
}

.history-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.history-item {
  padding: 10px;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.history-item:hover {
  background-color: #f5f7fa;
}

.history-item.active {
  background-color: #ecf5ff;
  color: #1a73e8;
}

.selection-panel {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin-bottom: 10px;
}

.form-item {
  margin-bottom: 20px;
}

.form-item label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: #333;
}

.action-panel {
  text-align: center;
  margin: 20px 0;
}

.model-response-card {
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.model-response-content {
  white-space: pre-wrap;
  word-break: break-word;
  font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
  font-size: 14px;
  line-height: 1.6;
  padding: 16px;
  background-color: #f9f9f9;
  border-radius: 4px;
  color: #303133;
  max-height: 400px;
  overflow-y: auto;
}

.exercises-list {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.exercise-item {
  border: 1px solid #e6e6e6;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
  background-color: #fff;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.exercise-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px dashed #e6e6e6;
}

.exercise-type {
  background-color: #409EFF;
  color: white;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 14px;
}

.exercise-number {
  font-size: 14px;
  color: #606266;
}

.question-title {
  font-size: 16px;
  line-height: 1.6;
  margin-bottom: 15px;
}

.exercise-options {
  margin-top: 12px;
  margin-left: 20px;
}

.option-item {
  margin-bottom: 10px;
  line-height: 1.5;
  display: flex;
  gap: 5px;
}

.exercise-footer {
  margin-top: 20px;
  border-top: 1px dashed #e6e6e6;
  padding-top: 15px;
}

.toggle-btn {
  margin-bottom: 10px;
}

.answer-section {
  background-color: #f8f8f8;
  padding: 15px;
  border-radius: 6px;
}

.answer-content {
  color: #67c23a;
  margin-bottom: 10px;
  font-size: 16px;
  line-height: 1.5;
}

.explanation-content {
  color: #606266;
  line-height: 1.6;
  text-align: justify;
}
</style> 